import groovy.json.JsonSlurper
import java.text.SimpleDateFormat

task packageApk {
    println("BUILD_TYPE:" + BUILD_TYPE)
    File apkFileDir = null
    dependsOn("assemble" + BUILD_TYPE.capitalize())
    if(BUILD_TYPE.equals("release")){
        apkFileDir = new File(project.buildDir, "outputs/apk/flavors_dev/release")
    }else{
        apkFileDir = new File(project.buildDir, "outputs/apk/flavors_dev/debug")
    }
    doLast {
        def uploadFile = findApkFile(apkFileDir)
        println("uploadFile:" + uploadFile.name)
        uploadApk(uploadFile)
    }
}

def findApkFile(File apkFile) {
    println("apkFile:" + apkFile.name)
    if (apkFile.isDirectory()) {
        def files = apkFile.listFiles()
        for (int i = 0; i < files.length; i++) {
            def findFile = findApkFile(files[i])
            if (findFile != null) {
                return findFile
            }
        }
    } else if (apkFile.name.endsWith(".apk")) {
        return apkFile
    } else return null
}

def uploadApk(File uploadApkFile) {
    // 查找上传的 apk 文件, 这里需要换成自己 apk 路径
    println("uploadApk:" + uploadApkFile.absolutePath + "--" + uploadApkFile.exists())
    if (uploadApkFile == null || !uploadApkFile.exists()) {
        throw new RuntimeException("apk file not exists!")
    }
    println "*************** upload start ***************"

    String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
    String PREFIX = "--", LINE_END = "\r\n";
    String CONTENT_TYPE = "multipart/form-data"; // 内容类型

    try {
        URL url = new URL("https://www.pgyer.com/apiv2/app/upload");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(30000);
        conn.setConnectTimeout(30000);
        conn.setDoInput(true); // 允许输入流
        conn.setDoOutput(true); // 允许输出流
        conn.setUseCaches(false); // 不允许使用缓存
        conn.setRequestMethod("POST"); // 请求方式
        conn.setRequestProperty("Charset", "UTF-8"); // 设置编码
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

        StringBuffer sb = new StringBuffer();
        sb.append(PREFIX).append(BOUNDARY).append(LINE_END);//分界符
        sb.append("Content-Disposition: form-data; name=\"" + "_api_key" + "\"" + LINE_END);
        sb.append("Content-Type: text/plain; charset=UTF-8" + LINE_END);
        //sb.append("Content-Transfer-Encoding: 8bit" + LINE_END);
        sb.append(LINE_END);
        sb.append("b49781d562ffc30585ec6d6b93d0c758");//替换成你再蒲公英上申请的apiKey
        sb.append(LINE_END);//换行！


        if (uploadApkFile != null) {
            /**
             * 当文件不为空，把文件包装并且上传
             */
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);
            /**
             * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
             * filename是文件的名字，包含后缀名的 比如:abc.png
             */
            sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + uploadApkFile.getName() + "\"" + LINE_END);
            sb.append("Content-Type: application/octet-stream; charset=UTF-8" + LINE_END);
            sb.append(LINE_END);
            dos.write(sb.toString().getBytes())

            InputStream is = new FileInputStream(uploadApkFile)
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
            }
            is.close();
            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();

            dos.write(end_data);
            dos.flush();
            /**
             * 获取响应码 200=成功 当响应成功，获取响应的流
             */
            int res = conn.getResponseCode();
            if (res == 200) {
                println("Upload request success");
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))
                StringBuffer ret = new StringBuffer();
                String line
                while ((line = br.readLine()) != null) {
                    ret.append(line)
                }
                String result = ret.toString();
                println("Upload result : " + result);

                def resp = new JsonSlurper().parseText(result)
                println result
                println "*************** upload finish ***************"
                sendMsgToDing(resp.data)
            } else {
                //发送钉钉 消息--构建失败
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

def sendMsgToDing(def data) {
    def conn = new URL("https://oapi.dingtalk.com/robot/send?access_token=e472cbda0a17b89c191646cdbc7429f5f43e653737d2f4db3c95c3d6ca5e24b9").openConnection()//替换成自己的钉钉webHook的url
    conn.setRequestMethod('POST')
    conn.setRequestProperty("Connection", "Keep-Alive")
    conn.setRequestProperty("Content-type", "application/json;charset=UTF-8")
    conn.setConnectTimeout(30000)
    conn.setReadTimeout(30000)
    conn.setDoInput(true)
    conn.setDoOutput(true)
    def dos = new DataOutputStream(conn.getOutputStream())

    def downloadUrl = "https://www.pgyer.com/" + data.buildShortcutUrl
    def qrCodeUrl = "![](" + data.buildQRCodeURL + ")"
    def detailLink = "[项目地址](${BUILD_URL})"

    def _title = "### 【${JOB_NAME}】构建成功"
    def _content = new StringBuffer()
    _content.append("\n\n### ${JOB_NAME}构建成功")
    _content.append("\n\n构建版本:${BRANCH_NAME}")
    _content.append("\n\n构建类型:${BUILD_TYPE}")
    _content.append("\n\n下载地址:" + downloadUrl)
    _content.append("\n\n" + qrCodeUrl)
    _content.append("\n\n构建用户:${BUILD_USER}")
    _content.append("\n\n构建时间:" + getNowTime())
    _content.append("\n\n查看详情:" + detailLink)
    def json = new groovy.json.JsonBuilder()
    json {
        msgtype "markdown"
        markdown {
            title _title
            text _content.toString()
        }
        at {
            atMobiles([])
            isAtAll false
        }
    }

    println(json)
    dos.writeBytes(json.toString())
    def input = new BufferedReader(new InputStreamReader(conn.getInputStream()))
    String line = ""
    String result = ""
    while ((line = input.readLine()) != null) {
        result += line
    }
    dos.flush()
    dos.close()
    input.close()
    conn.connect()
    println(result)

    println("*************** 钉钉消息已发送 ***************")
}

//获取当前时间
def getNowTime() {
    def str = "";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Calendar lastDate = Calendar.getInstance();
    str = sdf.format(lastDate.getTime());
    return str;
}